from . import db
from sqlalchemy import func

class Signal(db.Model):
    """信号表模型"""
    __tablename__ = 'signals'

    id = db.Column(db.Integer, primary_key=True)
    stock_code = db.Column(db.String(10), nullable=False)
    signal_date = db.Column(db.Date, nullable=False)
    # 状态: 'pending' (待测试), 'tested' (已测试)
    status = db.Column(db.String(20), nullable=False, default='pending')
    # 盈亏百分比, 允许为空
    pnl_pct = db.Column(db.Float, nullable=True)
    # 手动交易记录ID, 允许为空
    trade_log_id = db.Column(db.Integer, db.ForeignKey('manual_trades.id'), nullable=True)
    # 创建时间，默认为当前时间
    created_at = db.Column(db.DateTime, server_default=func.now())
    
    # 定义与ManualTrade的一对一关系
    trade_log = db.relationship('ManualTrade', backref='signal', uselist=False, foreign_keys=[trade_log_id])

    def to_dict(self):
        """将模型对象转换为字典，方便序列化为JSON"""
        return {
            'id': self.id,
            'stock_code': self.stock_code,
            'signal_date': self.signal_date.strftime('%Y-%m-%d'),
            'status': self.status,
            'pnl_pct': f"{self.pnl_pct:.2f}%" if self.pnl_pct is not None else "N/A",
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'trade_log_id': self.trade_log_id
        }


class ManualTrade(db.Model):
    """手动交易记录表模型"""
    __tablename__ = 'manual_trades'

    id = db.Column(db.Integer, primary_key=True)
    buy_date = db.Column(db.Date, nullable=False)
    buy_price = db.Column(db.Float, nullable=False)
    sell_date = db.Column(db.Date, nullable=False)
    sell_price = db.Column(db.Float, nullable=False)
    shares = db.Column(db.Integer, nullable=False)

    def to_dict(self):
        return {
            'id': self.id,
            'buy_date': self.buy_date.strftime('%Y-%m-%d'),
            'buy_price': self.buy_price,
            'sell_date': self.sell_date.strftime('%Y-%m-%d'),
            'sell_price': self.sell_price,
            'shares': self.shares
        } 